﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using Newtonsoft.Json;

namespace WFRPDice
{
    public static class WfrpDiceHelper
    {
        public static void Serialize(Stream streamObject, object obj)
        {
            if (obj == null || streamObject == null)
                return;
            var ser = new JsonSerializer();
            JsonWriter jw = new JsonTextWriter(new StreamWriter(streamObject));
            ser.Serialize(jw, obj);
            jw.Flush();
        }

        public static object Deserialize(Stream streamObject, Type objectType)
        {
            if (objectType == null || streamObject == null)
                return null;
            var ser = new JsonSerializer();
            JsonReader jr = new JsonTextReader(new StreamReader(streamObject));
            return ser.Deserialize(jr, objectType);
        }

        // Return a list of an enumerated type's values.
        public static List<T> GetEnumValues<T>()
        {
            // Get the type's Type information.
            Type tType = typeof (T);

            // Enumerate the Enum's fields.
            FieldInfo[] fieldInfos = tType.GetFields();

            // Loop over the fields.

            return (from fieldInfo in fieldInfos where fieldInfo.IsLiteral select (T) fieldInfo.GetValue(null)).ToList();
        }

        //Annoying but neccessary since I'm using enums to keep the names nice
        public static List<string> ConvertSymbolsToStrings()
        {
            List<DiceSymbol> allSymbols = GetEnumValues<DiceSymbol>();
            return allSymbols.Select(s => s.ToString()).ToList();
        }

        public static int GetDiceSymbolCount(DiceSymbol sym, List<DiceSymbol> res)
        {
            return res.Count(s => s == sym);
        }
    }
}